from django.contrib.auth.decorators import login_required
from django.utils.decorators import wraps
from django import http
from django.contrib.auth.mixins import AccessMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied

from meiduo_mall.utils.response_code import RETCODE


# def login_required_json(view_func):
#     """
#     判断用户是否登录的装饰器，并返回json
#     :param view_func: 被装饰的视图函数
#     :return: json、view_func
#     """
#     # 恢复view_func的名字和文档
#     @wraps(view_func)
#     def wrapper(request, *args, **kwargs):
#
#         # 如果用户未登录，返回json数据
#         if not request.user.is_authenticated():
#             return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
#         else:
#             # 如果用户登录，进入到view_func中
#             return view_func(request, *args, **kwargs)
#
#     return wrapper


# class LoginRequiredJSONMixin(object):
#     """验证用户是否登录并返回json的扩展类"""
#     @classmethod
#     def as_view(cls, **initkwargs):
#         view = super().as_view(**initkwargs)
#         return login_required_json(view)


# class LoginRequiredMixin(object):
#   """验证用户是否登录扩展类"""
#
#   @classmethod
#   def as_view(cls, **initkwargs):
#       # 自定义的as_view()方法中，调用父类的as_view()方法
#       view = super().as_view()
#       return login_required(view)


# class LoginRequiredJSONMixin(AccessMixin):
#   """
#   CBV mixin which verifies that the current user is authenticated.
#   """
#
#   def dispatch(self, request, *args, **kwargs):
#       if not request.user.is_authenticated:
#           return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
#       return super().dispatch(request, *args, **kwargs)


# class LoginRequiredJSONMixin(LoginRequiredMixin):
#     """Verify that the current user is authenticated."""
#
#     raise_exception = True
#
#     def dispatch(self, request, *args, **kwargs):
#         try:
#             return super().dispatch(request, *args, **kwargs)
#         except PermissionDenied:
#             return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})


class LoginRequiredJSONMixin(LoginRequiredMixin):
    """Verify that the current user is authenticated."""

    def handle_no_permission(self):
        return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})